class Array

Add some handy sorting methods to the Array class

Public Instance Methods

radix_sort(base=10) click to toggle source

Performs a radix sort of the array using a given base (default 10).

# File lib/utils.rb, line 22
def radix_sort(base=10)
  ary = dup
  rounds = (Math.log(self.max.abs)/Math.log(base)).ceil
  rounds.times do |i|
    buckets = Hash.new {|h,k| h[k] = []}
    ary.each do |n|
      digit = (n/base**i) % base
      digit = digit + base unless n<0
      buckets[digit] << n
    end
    ary = buckets.values_at(*(0..2*base)).compact.flatten
    p [i, ary] if $DEBUG
  end
  ary
end
radix_sort!(base=10) click to toggle source

Destructive version of #radix_sort

# File lib/utils.rb, line 40
def radix_sort!(base=10)
  replace radix_sort(base)
end